{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "80b3b059-7070-4908-98db-b3b5e792ede8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletionMessage(content=\"Hello! How can I assist you today? Whether you need help with a question, task, or just want to chat, I'm here for you.\", refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None)\n"
     ]
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=\"bce-v3/ALTAK-6eOzIHNDEa52NY1surh1q/18e798fe7ea302266c5f5ce740da0e43ad9c52e8\",  # 千帆bearer token\n",
    "    base_url=\"https://qianfan.baidubce.com/v2\"\n",
    ")\n",
    "\n",
    "completion = client.chat.completions.create(\n",
    "    model=\"ernie-4.0-turbo-8k\", # 预置服务请查看模型列表，定制服务请填入API地址\n",
    "    messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},\n",
    "              {'role': 'user', 'content': 'Hello！'}]\n",
    ")\n",
    "\n",
    "print(completion.choices[0].message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "75bf86f5-f357-4116-ad31-aad9d2f91c64",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletionMessage(content='\\n\\n比较20和11的大小，可以通过分析它们的位数来确定。\\n\\n1. **个位数比较**：\\n   - 20的个位数是0。\\n   - 11的个位数是1。\\n   - 0 < 1，所以在个位数上，11大于20。\\n\\n2. **十位数比较**：\\n   - 20的十位数是2。\\n   - 11的十位数是1。\\n   - 2 > 1，所以在十位数上，20大于11。\\n\\n综合来看，虽然11在个位数上较大，但20在十位数上较大。在整体数值比较中，十位数的差异起决定性作用。\\n\\n因此，\\\\(\\\\boxed{20}\\\\)', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None, reasoning_content='首先，我需要比较20和11这两个数的大小。\\n\\n我可以从个位数开始比较，个位数分别是0和1。\\n\\n因为0小于1，这意味着11在个位上大于20。\\n\\n接下来，我应该比较十位数，十位数分别是2和1。\\n\\n在这种情况下，2大于1，这表明20在十位上大于11。\\n\\n综合来看，20的十位数更大，因此20大于11。\\n')\n"
     ]
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    # 替换下列示例中参数，将your_APIKey替换为真实值，如何获取API Key请查看https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Um2wxbaps#步骤二-获取api-key\n",
    "    api_key=\"bce-v3/ALTAK-6eOzIHNDEa52NY1surh1q/18e798fe7ea302266c5f5ce740da0e43ad9c52e8\",\n",
    "    # 千帆ModelBuilder平台地址\n",
    "    base_url=\"https://qianfan.baidubce.com/v2\", \n",
    ")\n",
    "\n",
    "messages = [{\"role\": \"user\", \"content\": \"20和11，哪个数大?\"}] # 对话messages信息\n",
    "response = client.chat.completions.create(\n",
    "    model=\"deepseek-r1-distill-qwen-32b\",#模型对应的model值，请查看支持的模型列表：https://cloud.baidu.com/doc/WENXINWORKSHOP/s/wm7ltcvgc\n",
    "    messages=messages # messages信息\n",
    ")\n",
    "\n",
    "print(response.choices[0].message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "172f1acf-a9ac-4520-b7d3-abc03dba1935",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "RESTful API 是一种基于 HTTP 协议的设计风格，遵循 **REST（Representational State Transfer）** 架构原则。其核心是通过统一的接口和资源抽象来实现客户端与服务器的交互。以下是其主要设计原则及解释：\n",
      "\n",
      "---\n",
      "\n",
      "### 1. **资源导向（Resource-Based）**\n",
      "   - **URI 表示资源**：每个资源由唯一标识符（URI）表示，例如 `/users` 表示用户集合，`/users/123` 表示 ID 为 123 的用户。\n",
      "   - **名词化 URI**：URI 应使用名词（复数形式）而非动词，如 `/articles` 而不是 `/getArticles`。\n",
      "   - **分层结构**：复杂资源可通过层级 URI 表示，例如 `/users/123/orders` 表示用户 123 的订单集合。\n",
      "\n",
      "---\n",
      "\n",
      "### 2. **正确使用 HTTP 方法**\n",
      "   - **HTTP 动词定义操作**：利用标准 HTTP 方法（GET、POST、PUT、DELETE、PATCH）操作资源：\n",
      "     - `GET`：获取资源（安全且幂等）。\n",
      "     - `POST`：创建新资源（非幂等）。\n",
      "     - `PUT`：全量更新资源（幂等）。\n",
      "     - `DELETE`：删除资源（幂等）。\n",
      "     - `PATCH`：部分更新资源。\n",
      "   - **避免滥用 POST**：不推荐所有操作都用 POST（例如用 POST 代替 DELETE）。\n",
      "\n",
      "---\n",
      "\n",
      "### 3. **无状态性（Statelessness）**\n",
      "   - **请求独立性**：每个请求必须包含处理所需的所有信息（如认证 Token），服务器不保存客户端会话状态。\n",
      "   - **优点**：提高可扩展性和可靠性，简化服务器设计。\n",
      "\n",
      "---\n",
      "\n",
      "### 4. **资源的表述（Representation）**\n",
      "   - **数据格式分离**：资源与表现形式解耦。同一资源可返回 JSON、XML 等格式，通过 `Content-Type` 和 `Accept` 头协商（如 `Accept: application/json`）。\n",
      "   - **常见格式**：推荐使用 JSON 作为默认格式（轻量且易解析）。\n",
      "\n",
      "---\n",
      "\n",
      "### 5. **超媒体驱动（HATEOAS）**\n",
      "   - **响应中包含链接**：通过超媒体（Hypermedia）告知客户端下一步操作的可能路径。例如：\n",
      "     ```json\n",
      "     {\n",
      "       \"id\": 123,\n",
      "       \"name\": \"Alice\",\n",
      "       \"links\": [\n",
      "         { \"rel\": \"self\", \"href\": \"/users/123\" },\n",
      "         { \"rel\": \"orders\", \"href\": \"/users/123/orders\" }\n",
      "       ]\n",
      "     }\n",
      "     ```\n",
      "   - **动态发现 API**：客户端无需硬编码 URI，通过链接导航（实际应用中较少完全实现）。\n",
      "\n",
      "---\n",
      "\n",
      "### 6. **版本控制（Versioning）**\n",
      "   - **兼容性管理**：通过 URI（如 `/api/v1/users`）或请求头（如 `Accept: application/vnd.myapi.v1+json`）标识版本，避免破坏性变更影响旧客户端。\n",
      "\n",
      "---\n",
      "\n",
      "### 7. **过滤、排序与分页**\n",
      "   - **查询参数标准化**：使用 `filter`、`sort`、`page` 等参数处理集合资源，例如：\n",
      "     - `GET /users?country=US&sort=-created_at&page=2&limit=10`\n",
      "     - 分页响应中可包含总数和页数信息。\n",
      "\n",
      "---\n",
      "\n",
      "### 8. **错误处理**\n",
      "   - **HTTP 状态码**：明确的状态码（如 `200 OK`、`404 Not Found`、`400 Bad Request`、`500 Internal Server Error`）表示请求结果。\n",
      "   - **结构化错误信息**：返回错误详情，例如：\n",
      "     ```json\n",
      "     {\n",
      "       \"error\": {\n",
      "         \"code\": \"invalid_request\",\n",
      "         \"message\": \"Name cannot be empty.\"\n",
      "       }\n",
      "     }\n",
      "     ```\n",
      "\n",
      "---\n",
      "\n",
      "### 9. **缓存与性能优化**\n",
      "   - **利用 HTTP 缓存**：通过 `Cache-Control`、`ETag` 和 `Last-Modified` 头实现客户端或代理缓存，减少重复请求。\n",
      "\n",
      "---\n",
      "\n",
      "### 10. **安全性**\n",
      "   - **HTTPS 加密**：强制使用 HTTPS 保护数据传输。\n",
      "   - **认证与授权**：采用 OAuth 2.0、JWT 等机制，避免敏感信息（如密码）明文传输。\n",
      "   - **输入验证**：防止 SQL 注入、XSS 等攻击，严格校验参数。\n",
      "\n",
      "---\n",
      "\n",
      "### 总结\n",
      "RESTful API 的设计核心是 **简洁性**、**可扩展性** 和 **可维护性**。通过合理的资源建模、HTTP 方法语义化和标准化交互方式，使 API 易于理解和使用，同时充分利用 Web 基础设施（如缓存、HTTPS）提升性能与安全性。\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    # 请用知识引擎原子能力API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=\"sk-wh6uh5z1rZDZJGa9rDIYuxnMkE3phA6FKwWOwabI700kuVVV\", # 如何获取API Key：https://cloud.tencent.com/document/product/1772/115970\n",
    "    base_url=\"https://api.lkeap.cloud.tencent.com/v1\",\n",
    ")\n",
    "\n",
    "completion = client.chat.completions.create(\n",
    "    model=\"deepseek-r1\",  # 此处以 deepseek-r1 为例，可按需更换模型名称。\n",
    "    messages=[\n",
    "        {'role': 'user', 'content': '请解释一下RESTful API的设计原则'}\n",
    "        ]\n",
    ")\n",
    "\n",
    "print(completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85c7f8c0-e2b4-4e31-ba1b-229ff627de5c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "rag_learn",
   "language": "python",
   "name": "rag_learn"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
